import { SaaSUserInfo } from '/#/store';
import { defineStore } from 'pinia';

import { JumpLoginParams } from '/@/api/sys/model/userModel';
import { usePermissionStore } from '/@/store/modules/permission';
import { store } from '/@/store';
import { router } from '/@/router';

import { SaaSPageEnum } from '/@/enums/pageEnum';
import { oauthLogout } from '/@/api/sys/user';
import { useMessage } from '/@/hooks/web/useMessage';
import { h } from 'vue';
import { useI18n } from 'vue-i18n';

import {} from '../../utils/helper/envTransfrom';
import { cookies } from '../../utils/cookie/index';
import { isEmptyObject } from '../../utils/is';
import { getHomePathAndAddRoutes } from '../../router/helper/routeHelper';

interface SaaSUserState {
  userInfo: Partial<SaaSUserInfo>;
  token?: string;
}

export const useUserStore = defineStore({
  id: 'user',
  state: (): SaaSUserState => ({
    userInfo: {},
    token: undefined,
  }),

  getters: {
    getUserInfo(): Partial<SaaSUserInfo> {
      const userSessionInfo = cookies.get('userInfo') ? JSON.parse(cookies.get('userInfo')) : {};
      if (!isEmptyObject(this.userInfo)) {
        return this.userInfo;
      }
      if (!isEmptyObject(userSessionInfo)) {
        return userSessionInfo;
      }
      return {};
    },
    getToken(): string {
      return this.token || cookies.get('token') || '';
    },
  },
  actions: {
    setUserInfo(userInfo: Partial<SaaSUserInfo>) {
      this.userInfo = userInfo;
      cookies.set('userInfo', JSON.stringify(userInfo));
    },

    setToken(value: string) {
      this.token = value;
      cookies.set('token', value);
    },

    resetState() {
      this.userInfo = {};
      this.token = '';
      cookies.remove('token');
      cookies.remove('userInfo');
    },

    async getUserMenuAction(goHome?: boolean): Promise<SaaSUserInfo | null> {
      const permissionStore = usePermissionStore();
      permissionStore.isDynamicAddedRoute = false;
      let homePath = '';
      if (!permissionStore.isDynamicAddedRoute) {
        const query = {
          tenantCode: this.userInfo?.tenantCode || '',
          userId: this.userInfo?.userId || '',
        };
        await permissionStore.fetchHashPower();
        const routes = await permissionStore.buildRoutes(query);
        homePath = getHomePathAndAddRoutes(routes, router);
        permissionStore.setDynamicAddedRoute(true);
      }
      goHome && (await router.replace(homePath));
      return this.userInfo;
    },

    async jumpToApp(params: JumpLoginParams & { goHome?: boolean }): Promise<SaaSUserInfo | null> {
      try {
        const { goHome = true, ...userInfo } = params;
        this.setUserInfo(userInfo);
        this.setToken(userInfo.token);
        return this.getUserMenuAction(goHome);
      } catch (error) {
        return Promise.reject(error);
      }
    },

    async logout(goLogin = false) {
      try {
        const userInfo = this.getUserInfo;
        if (goLogin) {
          this.clearAllLoginInfo();
          router.push(SaaSPageEnum.BASE_LOGIN);
        } else {
          if (userInfo) {
            if (this.getToken) {
              await oauthLogout({
                sessionId: userInfo.sessionId as string,
              });
              // console app directly return to login page
              this.clearAllLoginInfo();
              router.push(SaaSPageEnum.BASE_LOGIN);
            }
          }
        }
      } catch {
        // eslint-disable-next-line no-console
        console.log('用户注销失败！');
        await this.setToken('');
      }
    },

    async clearAllLoginInfo() {
      /* eslint-disable */
      const permissionStore = usePermissionStore();
      /* eslint-disable */
      this.resetState();
      await permissionStore.resetState();
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLogOut() {
      const { createConfirm } = useMessage();
      const { t } = useI18n();
      createConfirm({
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('sys.app.logoutMessage')),
        onOk: async () => {
          await this.logout(false);
        },
        style: 'margin-bottom: 15%;',
      });
    },
  },
});

export function useUserStoreWithout() {
  return useUserStore(store);
}
